package com.ruicar.afs.cloud.basic.costexemptbill.controller;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.basic.api.corporate.dto.BasicPenaltyExemptDto;
import com.ruicar.afs.cloud.basic.common.entity.BasicExpenseRecord;
import com.ruicar.afs.cloud.basic.common.entity.BasicExpenseRecordDetail;
import com.ruicar.afs.cloud.basic.common.entity.BasicPenaltyInterest;
import com.ruicar.afs.cloud.basic.common.entity.BasicRepaymentPlan;
import com.ruicar.afs.cloud.basic.common.service.*;
import com.ruicar.afs.cloud.basic.costexemptbill.condition.BasicCostExemptBillCondition;
import com.ruicar.afs.cloud.basic.costexemptbill.vo.BasicCostExemptBillInfoVo;
import com.ruicar.afs.cloud.basic.proceeds.debit.service.BasicDebitRecordService;
import com.ruicar.afs.cloud.batch.service.AfsBatchInfoService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ExpenseStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.FeeTypeEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author HuangTao
 * @Date 2020/7/15 18:33
 * @description: 费用豁免单
 */
@RestController
@AllArgsConstructor
@RequestMapping("/basicCostExemptBillInfo")
public class BasicCostExemptBillController {

    private final BasicMainInfoService basicMainInfoService;
    private final BasicDebitRecordService basicDebitRecordService;
    private final BasicExpenseRecordService basicExpenseRecordService;
    private final BasicPenaltyInterestService basicPenaltyInterestService;
    private final BasicRepaymentPlanService basicRepaymentPlanService;
    private final AfsBatchInfoService afsBatchInfoService;
    private final BasicExpenseRecordDetailService basicExpenseRecordDetailService;

    public Date getBatchDate() {
        return DateUtil.parse(afsBatchInfoService.getSystemBatchInfo("icos").getBatchDate(), DatePattern.PURE_DATE_PATTERN);
    }

    @PostMapping("/getBasicCostList")
    @ApiOperation(value = "获取已激活合同信息数据 多条件")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<IPage<BasicCostExemptBillInfoVo>> getBasicCostList(@RequestBody BasicCostExemptBillCondition condition) {
        condition.setContractStatus(ContractStatusEnum.contractEffective.name());
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<List<BasicCostExemptBillInfoVo>> list = basicMainInfoService.getBasicCostBillList(page, condition);
        return IResponse.success(list);
    }

    @ApiOperation(value = "根据合同号查询罚息总额")
    @PostMapping("/findByContractNoBasicExpenseRecord")
    @Transactional(rollbackFor = Exception.class)
    public IResponse findByContractNoBasicExpenseRecord(@RequestParam("contractNo") String contractNo) {

        BasicCostExemptBillInfoVo basicCostExemptBillInfoVo = new BasicCostExemptBillInfoVo();
        List<BasicExpenseRecord> list = basicExpenseRecordService.list(Wrappers.<BasicExpenseRecord>query().lambda()
                .eq(BasicExpenseRecord::getContractNo, contractNo)
                .eq(BasicExpenseRecord::getStatus, ExpenseStatusEnum.unsettle)
                .eq(BasicExpenseRecord::getCostType, FeeTypeEnum.penalty)
        );
        if (list.size() == 0) {
            return new IResponse().setData(basicCostExemptBillInfoVo);
        }


//        basicCostExemptBillInfoVo.setNetOverdueAmt(list.get(0).getCostAmt().subtract(list.get(0).getReceivedAmt()).subtract(list.get(0).getExemptedAmt()));
        basicCostExemptBillInfoVo.setCostAmt(list.get(0).getRemainingAmt());
        return new IResponse().setData(basicCostExemptBillInfoVo);
    }

    @ApiOperation(value = "根据合同号查询费用总额")
    @PostMapping("/findByContractNobasicExpense")
    @Transactional(rollbackFor = Exception.class)
    public IResponse findByContractNobasicExpense(@RequestParam("contractNo") String contractNo) {
        List<BasicExpenseRecord> one = basicExpenseRecordService.list(
                Wrappers.<BasicExpenseRecord>query().lambda().eq(BasicExpenseRecord::getContractNo, contractNo)
        );
        BasicCostExemptBillInfoVo basicExpenseRecord = new BasicCostExemptBillInfoVo();
        BigDecimal expireCostAmt = BigDecimal.ZERO;
        for (BasicExpenseRecord basicExpenseRecord2 : one) {
            expireCostAmt = basicExpenseRecord2.getRemainingAmt().add(expireCostAmt);
        }
        List<BasicExpenseRecord> two = basicExpenseRecordService.list(
                Wrappers.<BasicExpenseRecord>query().lambda().eq(BasicExpenseRecord::getContractNo, contractNo)
                        .eq(BasicExpenseRecord::getCostType, FeeTypeEnum.penalty)
        );
        if (two.size() > 0 && EmptyUtils.isNotEmpty(two)) {
            for (BasicExpenseRecord basicExpenseRecord2 : two) {
                expireCostAmt =  expireCostAmt.subtract(basicExpenseRecord2.getRemainingAmt());
            }
        }
        basicExpenseRecord.setCostAmt(expireCostAmt);
        return new IResponse().setData(basicExpenseRecord);
    }

    @ApiOperation(value = "根据合同号码查询合同每期罚息明细")
    @PostMapping("/getBasicPenaltyInterest")
    public IResponse getBasicPenaltyInterest(@RequestParam("contractNo") String contractNo) {
        List<BasicPenaltyInterest> list = basicPenaltyInterestService.list(Wrappers.<BasicPenaltyInterest>lambdaQuery().
                eq(BasicPenaltyInterest::getContractNo, contractNo)
                .orderByAsc(BasicPenaltyInterest::getTermNo));
        for (BasicPenaltyInterest penaltyInterest : list) {
            penaltyInterest.setPenaltyAmt(penaltyInterest.getTotalPenalty().subtract(penaltyInterest.getExemptedAmt().add(penaltyInterest.getReceivedAmt())));
            penaltyInterest.setOverdueAmt(penaltyInterest.getTotalPenalty().subtract(penaltyInterest.getExemptedAmt().add(penaltyInterest.getReceivedAmt())));
            BasicRepaymentPlan RepaymentPlan = basicRepaymentPlanService.getOne(Wrappers.<BasicRepaymentPlan>lambdaQuery()
                    .eq(BasicRepaymentPlan::getContractNo, penaltyInterest.getContractNo())
                    .eq(BasicRepaymentPlan::getTermNo, penaltyInterest.getTermNo()));
            penaltyInterest.setRepaymentDate(RepaymentPlan.getActualPaymentDate());
        }
        return new IResponse().setData(list);
    }

    @PostMapping("/updatePenaltyInterest")
    @ApiOperation(value = "更新合同每期罚息明细")
    public IResponse updatePenaltyInterest(@RequestBody BasicPenaltyExemptDto condition) {
        return basicExpenseRecordService.updatePenaltyInterest(condition, this.getBatchDate());
    }

    @PostMapping("/penaltyExemptValid")
    @ApiOperation(value = "罚息豁免校验")
    public IResponse<String> valid(@RequestParam("contractNo") String contractNo) {

        List<BasicPenaltyInterest> list = basicPenaltyInterestService.list(Wrappers.<BasicPenaltyInterest>lambdaQuery().
                eq(BasicPenaltyInterest::getContractNo, contractNo)
                .orderByAsc(BasicPenaltyInterest::getTermNo));
        if (EmptyUtils.isEmpty(list)) {
            return new IResponse().setData("该合同未生成过罚息，无需豁免！");
        }
        if (!basicDebitRecordService.isAllowedChangeRecord(contractNo)) {
            return new IResponse().setData("该合同财务结算中，豁免罚息无法继续！");
        }
        //更新合同费用记录
        BasicExpenseRecord basicExpenseRecord = basicExpenseRecordService.getOne(Wrappers.<BasicExpenseRecord>lambdaQuery()
                .eq(BasicExpenseRecord::getContractNo, contractNo)
                .eq(BasicExpenseRecord::getCostType, FeeTypeEnum.penalty));
        if (ExpenseStatusEnum.settle.equals(basicExpenseRecord.getStatus())) {
            return new IResponse().setData("该合同费用已还清，豁免罚息无法继续！");
        }

        return new IResponse().setData(Boolean.TRUE.toString());
    }

    @PostMapping("/expenseByContract")
    @ApiOperation(value = "查询合同费用明细通过合同号")
    public IResponse<List<BasicExpenseRecordDetail>> expenseByContract(@RequestParam("contractNo") String contractNo) {

        List<BasicExpenseRecordDetail> list = basicExpenseRecordDetailService.list(Wrappers.<BasicExpenseRecordDetail>query().lambda()
                .eq(BasicExpenseRecordDetail::getContractNo, contractNo)
        );
        return new IResponse().setData(list);
    }

    @PostMapping("/interestByContract")
    @ApiOperation(value = "查询每期罚息明细通过合同号")
    public IResponse<List<BasicPenaltyInterest>> interestByContract(@RequestParam("contractNo") String contractNo) {
        List<BasicPenaltyInterest> list = basicPenaltyInterestService.list(Wrappers.<BasicPenaltyInterest>query().lambda()
                .eq(BasicPenaltyInterest::getContractNo, contractNo)
        );
        return new IResponse().setData(list);
    }
}
